package net.wexoo.onlinedivelog.reusable.validation;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.ValidationError;
import org.apache.wicket.validation.validator.PatternValidator;

public class AllowedCharactersValidator extends PatternValidator {
   private static final long serialVersionUID = 1L;
   private static final String[] allowedSpecialCharacters = {"-", "_", ".", "!", "?", "'"};

   public AllowedCharactersValidator() {
      this("[\\p{Alnum}" + buildSpecialCharacterString(false) + "]+");
   }

   public AllowedCharactersValidator(String pattern) {
      super(pattern);
   }

   @Override
   public void error(IValidatable<String> validatable) {

      ValidationError error = new ValidationError();
      error.addMessageKey(getClass().getSimpleName());
      error.setVariable("specialChars", buildSpecialCharacterString(true));
      validatable.error(error);
   }

   private static String buildSpecialCharacterString(boolean formattedForOutput) {
      StringBuilder specialCharacterStringBuilder = new StringBuilder("");

      for (int i = 0; i < allowedSpecialCharacters.length; i++) {
         if (formattedForOutput)
            specialCharacterStringBuilder.append(" ");
         specialCharacterStringBuilder.append(allowedSpecialCharacters[i]);
      }
      if (formattedForOutput)
         specialCharacterStringBuilder.append(" ");
      return specialCharacterStringBuilder.toString();
   }
}